<template>
    <div class="main-container">
        <TableBody>
            <template #header>
                <TableHeader :show-filter="false">
                    <template #search-content>
                        <AddButton @click="onAddItem"></AddButton>
                    </template>

                </TableHeader>
            </template>
            <template #default>
                <a-table :bordered="false" :loading="tableLoading" :data="dataList" :pagination="pagination"
                    :row-key="rowKey">
                    <template #columns>
                        <a-table-column v-for="item of tableColumns" :key="item.key" :align="item.align"
                            :title="(item.title as string)" :width="item.width" :data-index="(item.key as string)"
                            :fixed="item.fixed">
                            <template v-if="item.key === 'index'" #cell="{ rowIndex }">
                                {{ rowIndex + 1 }}
                            </template>

                            <template v-else-if="item.key === 'actions'" #cell="{ record }">
                                <a-space>
                                    <a-button status="success" size="mini" @click="onUpdateItem(record)">编辑</a-button>

                                    <a-button status="danger" size="mini" @click="onDeleteItem(record)">删除</a-button>
                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </template>
        </TableBody>

        <ModalDialog ref="modalDialogRef" :title="actionTitle" @confirm="editOk">
            <template #content>
                <a-form ref="formRef" :model="editData">

                    <a-form-item field="category" label="产品属性"
                        :rules="[{ required: true, message: '请输入产品属性' }, { minLength: 2, message: '类别名不能少于两个字' }]"
                        :validate-trigger="['change', 'input']">
                        <a-input v-model="editData.category" placeholder="" />
                    </a-form-item>
                    <a-form-item field="meterUnit" label="计量单位" :rules="[{ required: true, message: '请输入计量单位' }]"
                        :validate-trigger="['change', 'input']">
                        <a-input v-model="editData.meterUnit" placeholder="" />
                    </a-form-item>
                    <a-form-item field="countUnit" label="计数单位" :rules="[{ required: true, message: '请输入计数单位' }]"
                        :validate-trigger="['change', 'input']">
                        <a-input v-model="editData.countUnit" placeholder="" />
                    </a-form-item>

                </a-form>
            </template>
        </ModalDialog>

    </div>
</template>

<script lang="ts">
import { post, get } from '@/api/http'
import { useRowKey, useTable, useTableColumn, usePagination } from '@/hooks/table'
import { ModalDialogType } from '@/types/components'
import { Message, Modal, Form } from '@arco-design/web-vue'
import { defineComponent, toRaw, onMounted, ref, reactive, watch } from 'vue'


export default defineComponent({
    name: 'Warehouse',

    setup() {

        const table = useTable()
        const rowKey = useRowKey('id')
        const actionTitle = ref('添加系统类别')
        const tableColumns = useTableColumn([
            table.indexColumn,
            {
                title: '类别名称',
                key: 'category',
                dataIndex: 'category',
                width: 150,
            },
            {
                title: '计量单位',
                key: 'meterUnit',
                dataIndex: 'meterUnit',
                width: 150,
            },
            {
                title: '计数单位',
                key: 'countUnit',
                dataIndex: 'countUnit',
                width: 150,
            },
            {
                title: '操作',
                key: 'actions',
                dataIndex: 'actions',
                fixed: 'right',
                width: 150,
            },
        ])
        const formRef = ref<typeof Form>()
        const pagination = usePagination(doRefresh)
        // 搜索对象
        interface sysTypeModel {
            "id": number | string,
            "category": string,
            "meterUnit": string,
            "countUnit": string,

        }
        const searchData = reactive<sysTypeModel>({
            "id": '',
            "category": "",
            "meterUnit": "",
            "countUnit": "",
        })
        // 请求表格数据的方法
        function doRefresh() {
            post({
                url: 'SysCategory/list',
                data: {
                    ...toRaw(searchData),
                    page: pagination.page,
                    size: pagination.pageSize
                },
            })
                .then(({ data, code }) => {
                    if (code === 200) {

                        table.handleSuccess(data.records);
                        pagination.setTotalSize(data.total)
                    }

                })
                .catch(console.log)
        }

        // 修改 使用的对象
        const editData = reactive<sysTypeModel>({
            "id": '',
            "category": "",
            "meterUnit": "",
            "countUnit": "",
        })

        // 修改弹窗对象
        const modalDialogRef = ref<ModalDialogType | null>(null);

        function onAddItem() {
            editData.category = ''
            editData.id = ''
            editData.meterUnit = ''
            editData.countUnit = ''

            actionTitle.value = '添加类别'
            modalDialogRef.value?.toggle()
        }

        function onUpdateItem(item: sysTypeModel) {

            editData.category = item.category
            editData.countUnit = item.countUnit
            editData.meterUnit = item.meterUnit
            editData.id = item.id
            actionTitle.value = '编辑类别'

            modalDialogRef.value?.toggle()
        }
        function onDeleteItem(data: any) {
            Modal.confirm({
                title: '提示',
                content: '是否要删除此类别？',
                cancelText: '取消',
                okText: '删除',
                onOk: () => {
                    post({
                        url: 'SysCategory/delete',
                        data: [data.id]
                    }).then(({ code }) => {
                        if (code === 200) {
                            Message.success('删除成功')
                        } else {
                            Message.success('删除失败')
                        }
                    }).catch(() => {
                        Message.success('网络错误')
                    }).finally(() => {
                        doRefresh()
                    })
                },
            })
        }
        const gcList = ref<string[]>([])
        // 加载
        onMounted(() => {
            doRefresh()
        })

        // 仓库状态修改事件
        const stateChange = (id: number, e: any) => {
            post({
                url: 'shelve/update',
                data: {
                    id: id,
                    isStop: e ? '1' : '0'
                }
            }).then(({ code }) => {
                if (code === 200) {
                    Message.success('修改成功')
                } else {
                    Message.warning('修改失败')
                }
            })
        }



        const editOk = () => {
            formRef.value
                ?.validate()
                .then((error: any) => {
                    if (error) {
                        return
                    }

                    if (actionTitle.value === "添加类别") {
                        post({
                            url: 'SysCategory/save',
                            data: {
                                ...toRaw(editData)
                            }
                        }).then(({ data, code }) => {
                            if (code === 200) {
                                Message.success('添加成功')
                            } else {
                                Message.warning('添加失败')
                            }
                        }).catch((err) => {
                            Message.error('网络错误')
                        }).finally(() => {
                            modalDialogRef.value?.close()
                            doRefresh()
                        })
                    } else {
                        post({
                            url: 'SysCategory/update',
                            data: {
                                ...toRaw(editData)
                            }
                        }).then(({ data, code }) => {
                            if (code === 200) {
                                Message.success('修改成功')
                            } else {
                                Message.warning('修改失败')
                            }
                        }).catch(() => {
                            Message.error('网络错误')
                        }).finally(() => {
                            modalDialogRef.value?.close()
                            doRefresh()
                        })
                    }

                })
        }

        return {
            formRef,
            editOk,
            gcList,
            pagination,
            modalDialogRef,
            stateChange,
            searchData,
            rowKey,
            editData,
            tableColumns,
            actionTitle,
            ...table,
            onAddItem,
            onDeleteItem,
            onUpdateItem,
            doRefresh
        }
    },
})
</script>
